<?php
namespace Project_725\Model;

use TwinPeaks\Core as Core;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\TableGateway\Feature\RowGatewayFeature;

abstract class Base
{
	use Core\TAppInjector;
	
	/**
	 * @var \Zend\Db\Adapter\Adapter
	 */
	static protected $_adapter;
	
	/**
	 * @var
	 */
	protected $dbTabRow;
	
	/**
	 * @return void
	 */
	function __construct($dbTabRow)
	{
		$this->dbTabRow = $dbTabRow;
	}
	
	/**
	 * @return void
	 */
	protected function init($tableName, $primaryKey = 'id')
	{
		if (!isset(self::$_adapter))
			self::$_adapter = self::getApplication()->getDbAdapter();
		if (!isset(static::$_tableGW))
		{
			static::$_tableGW = new TableGateway($tableName, self::$_adapter,
				new RowGatewayFeature($primaryKey));
			static::$_tableGW->initialize();			
		}
	}
	
	/**
	 * @return integer
	 */
	static protected function getLastInsertedId()
	{
		$result = self::$_adapter->query('select lastval() as id')
			->execute()->current();
		
		return $result['id'];
	}
	
	/**
	 * @return mixed
	 */
	function __call($name, $args)
	{
		if (!isset($this->dbTabRow))
			return;
		
		if (method_exists($this->dbTabRow, $name))
			return call_user_func_array(array($this->dbTabRow, $name), $args);
		else
		{
			$prefix = substr($name, 0, 3);
			$tail = strtolower($name[3]) . substr($name, 4);
			$propName = strtolower(preg_replace('~([A-Z])~', '_$1', $tail));		
			if (strcasecmp('get', $prefix) == 0)
			{
				return $this->dbTabRow->{$propName};
			}
			elseif (strcasecmp('set', $prefix) == 0)
			{
				$this->dbTabRow->{$propName} = $args[0];
			}
		}
	}

	/**
	 * @return User|array|null
	 */
	static function getByColumn($columnName, $value, $returnColl = false)
	{
		static::init();	
		$rowSet = static::$_tableGW->select([$columnName => $value]);
		if (!$returnColl)
		{
			$row = $rowSet->current();
			return $row ? new static($row) : null;
		}
		else
		{
			$coll = [];
			foreach ($rowSet as $row)
				$coll[] = new static($row);
			
			return $coll;
		}
		return null;
	}
	
	/**
	 * Converts Postgres array to PHP one
	 * 
	 * @return array
	 */
	final static function PsqltoArray($arrStr)
	{
		$tmp = explode(',', trim($arrStr, '{}'));
		if (empty($tmp))
			return array();
		else
			return $tmp;
	}
	
	/**
	 * Converts PHP array to Postgres one
	 * 
	 * @return string
	 */
	final static function toPsqlArray($array)
	{
		return '{' . join(',', $array) . '}';
	}
	
	/**
	 * @return void
	 */
	function save()
	{
		$this->dbTabRow->save();
	}
	
	/**
	 * @return void
	 */
	function delete()
	{
		$this->dbTabRow->delete();
	}
}
